package com.iflytek.exam.service.impl;

import java.awt.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;

import com.iflytek.common.core.domain.entity.SysUser;
import com.iflytek.common.utils.DateUtils;
import com.iflytek.common.utils.SecurityUtils;
import com.iflytek.exam.domain.*;
import com.iflytek.exam.domain.Choice;
import com.iflytek.exam.dto.*;
import com.iflytek.exam.mapper.*;
import com.iflytek.exam.utils.StringSplitter;
import com.iflytek.exam.vo.ShortAnswerSubmitVo;
import com.iflytek.system.mapper.SysUserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.iflytek.exam.service.ICheckExamService;

/**
 * 批改试卷Service业务层处理
 *
 * @author KK
 * @date 2024-07-09
 */
@Service
public class CheckExamServiceImpl implements ICheckExamService {
    @Autowired
    private CheckExamMapper checkExamMapper;

    @Autowired
    private QuestionExamMapper questionExamMapper;

    @Autowired
    private ChoiceMapper choiceMapper;

    @Autowired
    private JudgeMapper judgeMapper;

    @Autowired
    private ShortAnswerMapper shortAnswerMapper;

    @Autowired
    private PaperInfoMapper paperInfoMapper;

    @Autowired
    private ExamGradeMapper examGradeMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private CreateExamMapper examMapper;

    /**
     * 查询批改试卷
     *
     * @param id 批改试卷主键
     * @return 批改试卷
     */
    @Override
    public CheckExam selectCheckExamById(Long id) {
        return checkExamMapper.selectCheckExamById(id);
    }

    /**
     * 查询批改试卷列表
     *
     * @param checkExam 批改试卷
     * @return 批改试卷
     */
    @Override
    public List<CheckExam> selectCheckExamList(CheckExam checkExam) {

        return checkExamMapper.selectCheckExamList(checkExam);


    }

    /**
     * 新增批改试卷
     *
     * @param checkExam 批改试卷
     * @return 结果
     */
    @Override
    public int insertCheckExam(CheckExam checkExam) {
        checkExam.setCreateTime(DateUtils.getNowDate());
        return checkExamMapper.insertCheckExam(checkExam);
    }

    /**
     * 修改批改试卷
     *
     * @param checkExam 批改试卷
     * @return 结果
     */
    @Override
    public int updateCheckExam(CheckExam checkExam) {
        return checkExamMapper.updateCheckExam(checkExam);
    }

    /**
     * 批量删除批改试卷
     *
     * @param ids 需要删除的批改试卷主键
     * @return 结果
     */
    @Override
    public int deleteCheckExamByIds(Long[] ids) {
        return checkExamMapper.deleteCheckExamByIds(ids);
    }

    /**
     * 删除批改试卷信息
     *
     * @param id 批改试卷主键
     * @return 结果
     */
    @Override
    public int deleteCheckExamById(Long id) {
        return checkExamMapper.deleteCheckExamById(id);
    }

    @Override
    public HashMap<String, Object> selectBasicInfo(Long examId) {
        //单选集合
        List<ChoiceCheckedDTO> singleCheckedDTOList = new ArrayList<>();
        //多选集合
        List<ChoiceCheckedDTO> multipleCheckedDTOList = new ArrayList<>();
        //判断集合
        List<JudgeCheckedDTO> judgeCheckedDTOList = new ArrayList<>();
        //简答集合
        List<ShortAnswerCheckedDTO> shortAnswerCheckedDTOList = new ArrayList<>();
        //查询所属试卷中所有的题号
        List<QuestionExam> questionExamList = questionExamMapper.selectQuestionExamListByExamIdAndUserId(examId,SecurityUtils.getUserId());
        if (questionExamList != null) {
            questionExamList.forEach(questionExam -> {
                if (questionExam.getType() == 1) {
                    Choice singleChoiceById = choiceMapper.selectChoiceById(questionExam.getQuestionId());
                    PaperInfo paperInfo = new PaperInfo();
                    paperInfo.setExamId(examId);
                    paperInfo.setQuId(questionExam.getQuestionId());
                    paperInfo.setType(questionExam.getType());
                    //查询提交的答案
                    PaperInfo paperInfoSelect = paperInfoMapper.selectPaperQuestionByQuIdAndExamIdAndType(paperInfo);
                    ChoiceCheckedDTO choiceCheckedDTO = new ChoiceCheckedDTO();
                    BeanUtils.copyProperties(singleChoiceById, choiceCheckedDTO);
                    //存储拆分的答案
                    choiceCheckedDTO.setSelectedAnswer(paperInfoSelect != null ? StringSplitter.splitString(paperInfoSelect.getContent()) : null);
                    choiceCheckedDTO.setAnswer(StringSplitter.splitString(singleChoiceById.getAnswer()));
                    singleCheckedDTOList.add(choiceCheckedDTO);
                }
                if (questionExam.getType() == 2) {
                    Choice multipleChoiceById = choiceMapper.selectChoiceById(questionExam.getQuestionId());
                    PaperInfo paperInfo = new PaperInfo();
                    paperInfo.setExamId(examId);
                    paperInfo.setQuId(questionExam.getQuestionId());
                    paperInfo.setType(questionExam.getType());
                    //查询提交的答案
                    PaperInfo paperInfoSelect = paperInfoMapper.selectPaperQuestionByQuIdAndExamIdAndType(paperInfo);
                    ChoiceCheckedDTO choiceCheckedDTO = new ChoiceCheckedDTO();
                    BeanUtils.copyProperties(multipleChoiceById, choiceCheckedDTO);
                    choiceCheckedDTO.setSelectedAnswer(paperInfoSelect != null ? StringSplitter.splitString(paperInfoSelect.getContent()) : null);
                    choiceCheckedDTO.setAnswer(StringSplitter.splitString(multipleChoiceById.getAnswer()));
                    multipleCheckedDTOList.add(choiceCheckedDTO);
                }
                if (questionExam.getType() == 3) {
                    Judge judgeById = judgeMapper.selectJudgeById(questionExam.getQuestionId());
                    if (judgeById == null) {
                        // 处理为 null 的情况，例如抛出异常、设置默认值或执行其他替代逻辑
                        throw new RuntimeException("未找到对应的 判断题 数据");
                    }
                    PaperInfo paperInfo = new PaperInfo();
                    paperInfo.setExamId(examId);
                    paperInfo.setQuId(questionExam.getQuestionId());
                    paperInfo.setType(questionExam.getType());
                    // 查询提交的答案
                    PaperInfo paperInfoSelect = paperInfoMapper.selectPaperQuestionByQuIdAndExamIdAndType(paperInfo);
                    JudgeCheckedDTO judgeCheckedDTO = new JudgeCheckedDTO();
                    BeanUtils.copyProperties(judgeById, judgeCheckedDTO);
                    judgeCheckedDTO.setSelectedAnswer(paperInfoSelect != null ? StringSplitter.splitString(paperInfoSelect.getContent()) : null);
                    judgeCheckedDTOList.add(judgeCheckedDTO);
                }
                if (questionExam.getType() == 4) {
                    Long userId = SecurityUtils.getUserId();
                    ExamGrade examGrade = examGradeMapper.selectExamGradeByExamIdAndUserId(examId, userId);
                    //试卷已批阅的时候才给学生返回简答题的答案
                    if (examGrade.getStatus() == 1) {
                        ShortAnswer shortAnswerById = shortAnswerMapper.selectShortAnswerById(questionExam.getQuestionId());
                        PaperInfo paperInfo = new PaperInfo();
                        paperInfo.setExamId(examId);
                        paperInfo.setQuId(questionExam.getQuestionId());
                        paperInfo.setType(questionExam.getType());
                        //查询提交的答案
                        PaperInfo paperInfoSelect = paperInfoMapper.selectPaperQuestionByQuIdAndExamIdAndType(paperInfo);
                        ShortAnswerCheckedDTO shortAnswerCheckedDTO = new ShortAnswerCheckedDTO();
                        BeanUtils.copyProperties(shortAnswerById, shortAnswerCheckedDTO);
                        shortAnswerCheckedDTO.setSelectedAnswer(paperInfoSelect != null ? paperInfoSelect.getContent() : null);
                        shortAnswerCheckedDTOList.add(shortAnswerCheckedDTO);
                    }
                }
            });
        } else {
            return null;
        }
        ExamGrade examGrade = examGradeMapper.selectExamGradeByExamId(examId);
        SysUser sysUser = sysUserMapper.selectUserById(SecurityUtils.getUserId());
        HashMap<String, Object> examDetails = new HashMap<>();
        examDetails.put("examId", examId);
        Optional<ExamGrade> optionalExamGrade = Optional.ofNullable(examGrade);
        examDetails.put("time", optionalExamGrade.map(ExamGrade::getTime).orElse(0));
        examDetails.put("username", sysUser.getUserName());
        examDetails.put("totalScore", examGrade.getTotalScore());
        examDetails.put("single", singleCheckedDTOList);
        examDetails.put("multiple", multipleCheckedDTOList);
        examDetails.put("judge", judgeCheckedDTOList);
        examDetails.put("shortAnswer", shortAnswerCheckedDTOList);
        return examDetails;
    }

    @Override
    public int updateScore(List<ShortAnswerSubmitVo> shortAnswerSubmitVos) {
        AtomicReference<Long> score = new AtomicReference<>(0L);
        if (shortAnswerSubmitVos != null && shortAnswerSubmitVos.size() > 0) {
            ExamGrade examGrade = examGradeMapper.selectExamGradeByExamId(shortAnswerSubmitVos.get(0).getExamId());
            CreateExam createExam = examMapper.selectcreateExamById(shortAnswerSubmitVos.get(0).getExamId());
            shortAnswerSubmitVos.forEach(shortAnswerSubmitVo -> {
                score.updateAndGet(v -> v + shortAnswerSubmitVo.getScore());
            });
            examGrade.setStatus(1);
            if ((examGrade.getSingleTotalScore() + examGrade.getMultipleTotalScore() + examGrade.getJudgeTotalScore() + examGrade.getShortAnswerTotalScore()) >= createExam.getPassLine()) {
                examGrade.setIsPass(1);
            }
            //更新成绩
            return examGradeMapper.updateExamGrade(examGrade);
        }
        return 0;
    }

    @Override
    public HashMap<String, Object> checkBasicInfo(Long gradeId) {
        //单选集合
        List<ChoiceCheckedDTO> singleCheckedDTOList = new ArrayList<>();
        //多选集合
        List<ChoiceCheckedDTO> multipleCheckedDTOList = new ArrayList<>();
        //判断集合
        List<JudgeCheckedDTO> judgeCheckedDTOList = new ArrayList<>();
        //简答集合
        List<ShortAnswerCheckedDTO> shortAnswerCheckedDTOList = new ArrayList<>();
        //查询试卷id
        ExamGrade examGradeById = examGradeMapper.selectExamGradeById(gradeId);
        //查询所属试卷中所有的题号
        List<QuestionExam> questionExamList = questionExamMapper.selectQuestionExamListByExamIdAndUserId(examGradeById.getExamId(), examGradeById.getUserId());
        if (questionExamList != null) {
            questionExamList.forEach(questionExam -> {
                if (questionExam.getType() == 1) {
                    Choice singleChoiceById = choiceMapper.selectChoiceById(questionExam.getQuestionId());
                    PaperInfo paperInfo = new PaperInfo();
                    paperInfo.setExamId(questionExam.getExamId());
                    paperInfo.setQuId(questionExam.getQuestionId());
                    paperInfo.setType(questionExam.getType());
                    //查询提交的答案
                    PaperInfo paperInfoSelect = paperInfoMapper.selectPaperQuestionByQuIdAndExamIdAndType(paperInfo);
                    ChoiceCheckedDTO choiceCheckedDTO = new ChoiceCheckedDTO();
                    BeanUtils.copyProperties(singleChoiceById, choiceCheckedDTO);
                    //存储拆分的答案
                    choiceCheckedDTO.setSelectedAnswer(paperInfoSelect != null ? StringSplitter.splitString(paperInfoSelect.getContent()) : null);
                    choiceCheckedDTO.setAnswer(StringSplitter.splitString(singleChoiceById.getAnswer()));
                    singleCheckedDTOList.add(choiceCheckedDTO);
                }
                if (questionExam.getType() == 2) {
                    Choice multipleChoiceById = choiceMapper.selectChoiceById(questionExam.getQuestionId());
                    PaperInfo paperInfo = new PaperInfo();
                    paperInfo.setExamId(questionExam.getExamId());
                    paperInfo.setQuId(questionExam.getQuestionId());
                    paperInfo.setType(questionExam.getType());
                    //查询提交的答案
                    PaperInfo paperInfoSelect = paperInfoMapper.selectPaperQuestionByQuIdAndExamIdAndType(paperInfo);
                    ChoiceCheckedDTO choiceCheckedDTO = new ChoiceCheckedDTO();
                    BeanUtils.copyProperties(multipleChoiceById, choiceCheckedDTO);
                    choiceCheckedDTO.setSelectedAnswer(paperInfoSelect != null ? StringSplitter.splitString(paperInfoSelect.getContent()) : null);
                    choiceCheckedDTO.setAnswer(StringSplitter.splitString(multipleChoiceById.getAnswer()));
                    multipleCheckedDTOList.add(choiceCheckedDTO);
                }
                if (questionExam.getType() == 3) {
                    Judge judgeById = judgeMapper.selectJudgeById(questionExam.getQuestionId());
                    PaperInfo paperInfo = new PaperInfo();
                    paperInfo.setExamId(questionExam.getExamId());
                    paperInfo.setQuId(questionExam.getQuestionId());
                    paperInfo.setType(questionExam.getType());
                    //查询提交的答案
                    PaperInfo paperInfoSelect = paperInfoMapper.selectPaperQuestionByQuIdAndExamIdAndType(paperInfo);
                    JudgeCheckedDTO judgeCheckedDTO = new JudgeCheckedDTO();
                    BeanUtils.copyProperties(judgeById, judgeCheckedDTO);
                    judgeCheckedDTO.setSelectedAnswer(paperInfoSelect != null ? StringSplitter.splitString(paperInfoSelect.getContent()) : null);
                    judgeCheckedDTOList.add(judgeCheckedDTO);
                }
                if (questionExam.getType() == 4) {
                    //直接给老师返回所有试题及答案信息
                    ShortAnswer shortAnswerById = shortAnswerMapper.selectShortAnswerById(questionExam.getQuestionId());
                    PaperInfo paperInfo = new PaperInfo();
                    paperInfo.setExamId(questionExam.getExamId());
                    paperInfo.setQuId(questionExam.getQuestionId());
                    paperInfo.setType(questionExam.getType());
                    //查询提交的答案
                    PaperInfo paperInfoSelect = paperInfoMapper.selectPaperQuestionByQuIdAndExamIdAndType(paperInfo);
                    ShortAnswerCheckedDTO shortAnswerCheckedDTO = new ShortAnswerCheckedDTO();
                    BeanUtils.copyProperties(shortAnswerById, shortAnswerCheckedDTO);
                    shortAnswerCheckedDTO.setSelectedAnswer(paperInfoSelect != null ? paperInfoSelect.getContent() : null);
                    shortAnswerCheckedDTOList.add(shortAnswerCheckedDTO);
                }
            });
        } else {
            return null;
        }
        ExamGrade examGrade = examGradeMapper.selectExamGradeById(gradeId);
        HashMap<String, Object> examDetails = new HashMap<>();
        examDetails.put("examId", examGradeById.getExamId());
        examDetails.put("time", examGrade.getTime() == null ? 0 : examGrade.getTime() );
        examDetails.put("username", sysUserMapper.selectUserById(examGradeById.getUserId()).getNickName());
        examDetails.put("totalScore", examGrade.getTotalScore());
        examDetails.put("single", singleCheckedDTOList);
        examDetails.put("multiple", multipleCheckedDTOList);
        examDetails.put("judge", judgeCheckedDTOList);
        examDetails.put("shortAnswer", shortAnswerCheckedDTOList);
        return examDetails;
    }


    /**
     * 老师查看试卷
     *
     * @param examId
     * @return
     */
    @Override
    public HashMap<String, Object> reviewBasicInfo(Long examId) {
        //单选集合
        List<ChoiceCheckedDTO> singleCheckedDTOList = new ArrayList<>();
        //多选集合
        List<ChoiceCheckedDTO> multipleCheckedDTOList = new ArrayList<>();
        //判断集合
        List<JudgeCheckedDTO> judgeCheckedDTOList = new ArrayList<>();
        //简答集合
        List<ShortAnswerCheckedDTO> shortAnswerCheckedDTOList = new ArrayList<>();
        //TODO 目前重复查询数据了，需要去重
        List<QuestionExam> questionExamList = questionExamMapper.selectQuestionExamList(examId);
        if (questionExamList != null && questionExamList.size() > 0) {
            questionExamList.forEach(questionExam -> {
                if (questionExam.getType() == 1) {
                    Choice singleChoiceById = choiceMapper.selectChoiceById(questionExam.getQuestionId());
                    ChoiceCheckedDTO choiceCheckedDTO = new ChoiceCheckedDTO();
                    BeanUtils.copyProperties(singleChoiceById, choiceCheckedDTO);
                    choiceCheckedDTO.setAnswer(StringSplitter.splitString(singleChoiceById.getAnswer()));
                    singleCheckedDTOList.add(choiceCheckedDTO);
                }
            });
            questionExamList.forEach(questionExam -> {
                if (questionExam.getType() == 2) {
                    Choice singleChoiceById = choiceMapper.selectChoiceById(questionExam.getQuestionId());
                    ChoiceCheckedDTO choiceCheckedDTO = new ChoiceCheckedDTO();
                    BeanUtils.copyProperties(singleChoiceById, choiceCheckedDTO);
                    choiceCheckedDTO.setAnswer(StringSplitter.splitString(singleChoiceById.getAnswer()));
                    multipleCheckedDTOList.add(choiceCheckedDTO);
                }
            });
            questionExamList.forEach(questionExam -> {
                if (questionExam.getType() == 3) {
                    Judge judgeById = judgeMapper.selectJudgeById(questionExam.getQuestionId());
                    JudgeCheckedDTO judgeCheckedDTO = new JudgeCheckedDTO();
                    BeanUtils.copyProperties(judgeById, judgeCheckedDTO);
                    judgeCheckedDTO.setAnswer(judgeById.getAnswer());
                    judgeCheckedDTOList.add(judgeCheckedDTO);
                }
            });
            questionExamList.forEach(questionExam -> {
                if (questionExam.getType() == 4) {
                    ShortAnswer shortAnswerById = shortAnswerMapper.selectShortAnswerById(questionExam.getQuestionId());
                    ShortAnswerCheckedDTO shortAnswerCheckedDTO = new ShortAnswerCheckedDTO();
                    BeanUtils.copyProperties(shortAnswerById, shortAnswerCheckedDTO);
                    shortAnswerCheckedDTO.setAnswer(shortAnswerById.getAnswer());
                    shortAnswerCheckedDTOList.add(shortAnswerCheckedDTO);
                }
            });
        }
        CreateExam examGrade = examMapper.selectcreateExamById(examId);
        HashMap<String, Object> examDetails = new HashMap<>();
        examDetails.put("examId", examId);
        examDetails.put("time", examGrade.getTime());
        examDetails.put("totalScore", examGrade.getTotalScore());
        examDetails.put("single", singleCheckedDTOList);
        examDetails.put("multiple", multipleCheckedDTOList);
        examDetails.put("judge", judgeCheckedDTOList);
        examDetails.put("shortAnswer", shortAnswerCheckedDTOList);
        //返回老师要查看的试卷题目详细信息
        return examDetails;
    }
}
